package com.webserver.core;

import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.net.URISyntaxException;

public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run(){
        try {
            HttpServletRequest request = new HttpServletRequest(socket);
            HttpServletResponse response = new HttpServletResponse(socket);
            String path = request.getUri();
            System.out.println("path:"+path);
            File root = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir = new File(root,"static");
            File file = new File(staticDir,path);
            if (file.isFile()){
                response.setEntity(file);
            }else {
                response.setStatusCode(404);
                response.setStatusReason("Not Found");
                file = new File(staticDir, "404.html");
                response.setEntity(file);
            }
            response.response();
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }
}
